﻿#include "EchoClient.h"
#include <QDebug>

EchoClient::EchoClient(const QUrl& url, bool debug, QObject* parent)
    : QObject(parent), m_url(url), m_debug(debug)
{
  if (m_debug)
  {
    qDebug() << "WebSocket server:" << url;
  }

  connect(&webSocket, &QWebSocket::connected, this, &EchoClient::onConnected);
  connect(&webSocket, SIGNAL(error(QAbstractSocket::SocketError)), this,
          SLOT(onError(QAbstractSocket::SocketError)));
  connect(&webSocket, &QWebSocket::disconnected, this, &EchoClient::onDisconnected);
  connect(&webSocket, &QWebSocket::textMessageReceived, this, &EchoClient::onTextMessageReceived);
  connect(&webSocket, &QWebSocket::binaryMessageReceived, this,
          &EchoClient::onBinaryMessageReceived);
  connect(&webSocket, &QWebSocket::pong, this, &EchoClient::onPong);

  connectToServer();
}

void EchoClient::onConnected()
{
  qDebug() << "WebSocket connected";
  if (m_debug) qDebug() << "WebSocket connected";
  connect(&webSocket, &QWebSocket::textMessageReceived, this, &EchoClient::onTextMessageReceived);
  webSocket.sendTextMessage(QStringLiteral("Hello, world!"));
}

void EchoClient::connectToServer()
{
  webSocket.open(m_url);
}

void EchoClient::onTextMessageReceived(QString message)
{
  if (m_debug) qDebug() << "Message received:" << message;
  webSocket.close();
}

void EchoClient::closed() {}

void EchoClient::onDisconnected()
{
  qDebug() << u8":断开连接";
}

void EchoClient::onBinaryMessageReceived(const QByteArray& message)
{
  qDebug() << message;
}

void EchoClient::onPong(quint64 elapsedTime, const QByteArray& payload)
{
  qDebug() << elapsedTime;
}

void EchoClient::onError(QAbstractSocket::SocketError error)
{
  qDebug() << error;
}
